package com.andnnl.vcode;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Tuple;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import java.io.File;
import java.math.BigInteger;
import java.net.Proxy;

/**
 * Created by chenss on 2021/6/24.
 */
public class YingdianDownload {
    public static final int GET_CODE_TIMES = 3;//获取验证码最多5次
    public static final int SEND_TIMES = 19;//发送最多3次
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 10000;

    public static void main(String[] args) throws InterruptedException {
        String dir = "E:\\yingdian_vcode.train3\\";
        String dir2 = "E:\\yingdian_vcode.test3\\";
        File dir11 = new File(dir);
        dir11.mkdirs();
        File dir22 = new File(dir2);
        dir22.mkdirs();
        String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
        for (int i = 1; i <= 1000; i++) {
//                downloadPic(downURL, downAddress + i + ".jpg");
            String fn = dir + ("" + (i + 10000)).substring(1, 5) + ".jpg";
            System.out.println(fn);
            getCode(userAgent, "", null, fn);
            Thread.sleep(10);
        }

    }

    private static int getRandomInt() {
        return (int) (System.currentTimeMillis() / 1000);
    }

    private static Tuple getCode(String userAgent, String cookiesStr, Proxy proxy, String fn) {
        HttpResponse rs;//下载验证码图片
        String getCodeUrl = "https://mvhere.com/WebLogin.jy/createCode?v=" + getRandomInt();
        HttpRequest request = HttpUtil.createGet(getCodeUrl);
        request.cookie(cookiesStr);
        request.header(Header.USER_AGENT, userAgent)
                .header(Header.REFERER, "https://mvhere.com/Index.jy")
                .setConnectionTimeout(CONNECTION_TIMEOUT)
                .setReadTimeout(READ_TIMEOUT)
                .setFollowRedirects(true);
        if (proxy != null)
            request.setProxy(proxy);
        rs = request.execute();//执行下载
        byte[] imgBytes = rs.bodyBytes();
        FileUtil.writeBytes(imgBytes, fn);//写到文件
        return null;
    }
}
